package com.mediacloud.app.newsmodule.view;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.media.MediaMetadata;
import android.media.session.PlaybackState;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.IBinder;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;

import com.bumptech.glide.Glide;
import com.chinamcloud.audioserver.APSLifecycleKit;
import com.chinamcloud.audioserver.MusicEntity;
import com.lzf.easyfloat.interfaces.OnPermissionResult;
import com.lzf.easyfloat.permission.PermissionUtils;
import com.mediacloud.app.assembly.util.Utility;
import com.mediacloud.app.assembly.views.ImageButtonX;
import com.mediacloud.app.assembly.views.NetImageViewX;
import com.mediacloud.app.model.news.ArticleItem;
import com.mediacloud.app.model.news.CatalogItem;
import com.mediacloud.app.newsmodule.R;
import com.mediacloud.app.newsmodule.activity.StopReadNewsEvent;
import com.mediacloud.app.newsmodule.activity.StyleSetActivity;
import com.mediacloud.app.newsmodule.service.AudioItem;
import com.mediacloud.app.newsmodule.utils.ToastUtil;
import com.mediacloud.app.reslib.enums.XKey;
import com.tencent.mmkv.MMKV;
import com.utils.SystemServiceManager;
import com.utils.read.AudioFloatManager;


import org.greenrobot.eventbus.EventBus;

import tv.danmaku.ijk.media.player.IMediaPlayer;

/**
 * Created by x on 2017/3/31.
 * 用在WebView里面的音频播放器界面
 */

public class WebInsertAudioView extends FrameLayout implements View.OnClickListener {

    protected TextView play_progress, total_progress;
    protected ImageButtonX audio_play;
    protected NetImageViewX audio_logo;
    protected TextView audio_title;
    public InsertAudioItem audioItem;
    public OnPositionListener onPositionListener;


    boolean isDispose = false;

    public IntserAudioActionListener intserAudioActionListener;
    CatalogItem catalogItem;
    Context mContext;
    ImageView audioPlayStatus;
    View toggleBtnContainer;
    public final String WebAudioID = "Web_Audio_ID";
    public final String AudioIndex = "AudioIndex";

    SeekBar audioSeekBar;
    APSLifecycleKit apsKit;

    public WebInsertAudioView(Context context, CatalogItem catalogItem) {
        super(context);
        mContext = context;
        this.catalogItem = catalogItem;
        LayoutInflater.from(context).inflate(R.layout.aappfactory_imgtxt_news_audioplayer, this);
        init();

    }

    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();
        if (getChildCount() > 0) {
            getChildAt(0).setPaddingRelative(0, 0, 0, 0);
        }
    }

    public void setAudioData(InsertAudioItem value) {
        this.audioItem = value;
        if (audioItem != null && audioItem.articleItem != null) {
            if (audioItem.streamInfo != null) {
                if(!TextUtils.isEmpty(audioItem.streamInfo.audioName)){
                    audio_title.setText(audioItem.streamInfo.audioName);
                }else {
                    audio_title.setVisibility(View.GONE);
                }
            }
            play_progress.setText("00:00");
            audio_logo.setBackgroundColor(Color.TRANSPARENT);

        }
        long audioId = MMKV.defaultMMKV().getLong(WebAudioID, -1);
        int audioIndex = MMKV.defaultMMKV().getInt(AudioIndex, -1);
        boolean resume = audioId == audioItem.articleItem.getId();
        initAPS(getContext(), audioItem.articleItem.getId() + "_" + getTag(), resume);

        if (resume) {
            clear();
            if (audioIndex == (int) getTag()) {
                if (intserAudioActionListener != null) {
                    intserAudioActionListener.triggerPlayAction(this,apsKit);
                }
                postDelayed(() -> {
                    if (mContext == null) {
                        return;
                    }
                    if (onPositionListener != null) {
                        onPositionListener.onPosition(getTop());
                    }
                }, 500);
            }
        }
    }

    public void pause() {
        if (apsKit.isTaskPlaying()) {
            apsKit.toggle();
        }
    }


    private void initAPS(Context context, String taskId, boolean resume) {
        if (!TextUtils.isEmpty(audioItem.articleItem.getProp4())){
            String time = audioItem.articleItem.getProp4();
//            if (time.startsWith("00:")){
//                time =  time.replace("00:","");
//            }
            total_progress.setText(time);
        }
        apsKit = new APSLifecycleKit(context, taskId, audioSeekBar, new APSLifecycleKit.APSCallback() {
            @Override
            public void onServiceConnected(@Nullable ComponentName name, @Nullable IBinder iBinder) {
                super.onServiceConnected(name, iBinder);
                if (resume) {
                    activate = true;
                    MusicEntity entity = new MusicEntity(audioItem.articleItem.getTitle(), audioItem.streamInfo.url);
                    apsKit.setData(entity);
                }
            }

            @Override
            public void onBufferingUpdate(@Nullable IMediaPlayer mediaPlayer, int percent) {
                super.onBufferingUpdate(mediaPlayer, percent);
            }

            @Override
            public void onCompletion(@Nullable IMediaPlayer mediaPlayer) {
                super.onCompletion(mediaPlayer);
                if(mContext!=null){
                Drawable toggleDrawable = mContext.getResources().getDrawable(R.drawable.insert_audio_playbtn);
                audio_play.normalImg = audio_play.pressImg = toggleDrawable;
                audio_play.updateEffDrawable();
                audioPlayStatus.setImageResource(R.drawable.instert_audio_playstatus);
            }
            }

            @Override
            public void onMetadataChanged(@Nullable MediaMetadata metadata) {
                super.onMetadataChanged(metadata);
            }

            @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
            @Override
            public void onPlaybackStateChanged(@Nullable PlaybackState state) {
                switch (state.getState()) {

                    case PlaybackState.STATE_NONE://无任何状态
                    case PlaybackState.STATE_STOPPED:
                        play_progress.setText("00:00");
                    case PlaybackState.STATE_PAUSED:

                        updateToggleDrawable();
                        break;
                    case PlaybackState.STATE_PLAYING:
                        updateToggleDrawable();
                        break;
                    case PlaybackState.STATE_SKIPPING_TO_NEXT://下一首
                        break;
                    case PlaybackState.STATE_SKIPPING_TO_PREVIOUS://上一首
                        break;
                    case PlaybackState.STATE_FAST_FORWARDING://快进
                        break;
                    case PlaybackState.STATE_REWINDING://快退
                        break;
                    case PlaybackState.STATE_ERROR:
                        com.utils.ToastUtil.showToastCenter(context, "出错了", Toast.LENGTH_SHORT);

                        break;
                }
            }

            @Override
            public void onPrepared(@Nullable IMediaPlayer mediaPlayer) {
                super.onPrepared(mediaPlayer);
                total_progress.setText(APSLifecycleKit.turnTime((int) (mediaPlayer.getDuration() / 1000)));
            }

            @Override
            public void onUpdateProgress(@Nullable IMediaPlayer mediaPlayer) {
                super.onUpdateProgress(mediaPlayer);
                play_progress.setText(APSLifecycleKit.turnTime((int) (mediaPlayer.getCurrentPosition() / 1000)));
            }
        });
    }

    protected void init() {
        audioSeekBar = Utility.findViewById(this, R.id.audioSeek);
        total_progress = Utility.findViewById(this, R.id.total_progress);
        audio_logo = Utility.findViewById(this, R.id.audio_logo);
        audio_play = Utility.findViewById(this, R.id.audio_p);
        play_progress = Utility.findViewById(this, R.id.play_progress);
        audio_title = Utility.findViewById(this, R.id.audio_title);
        audioPlayStatus = Utility.findViewById(this, R.id.audioPlayStatus);
        audio_title.setHorizontallyScrolling(true);
        toggleBtnContainer = Utility.findViewById(this, R.id.toggleBtnContainer);
        audio_title.setText("");
        audio_title.setSelected(true);
        play_progress.setText("00:00");
        audio_play.setOnClickListener(this);

    }

    protected void initNetStatusBroad() {
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
        intentFilter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
        intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        receiver = new NetChangeReceiver();
        getContext().registerReceiver(receiver, intentFilter);

    }
    public void updateToggleDrawable() {
        if (mContext == null)
            return;
        Drawable toggleDrawable;
        if (apsKit.isTaskPlaying()) {
            toggleDrawable = mContext.getResources().getDrawable(R.drawable.insert_audio_pausebtn);
            Glide.with(mContext).load(R.drawable.instert_audio_playstatus).into(audioPlayStatus);
        } else {
            toggleDrawable = mContext.getResources().getDrawable(R.drawable.insert_audio_playbtn);
            audioPlayStatus.setImageResource(R.drawable.instert_audio_playstatus);
        }
        audio_play.normalImg = audio_play.pressImg = toggleDrawable;
        audio_play.updateEffDrawable();
    }


    private void clear() {
        MMKV.defaultMMKV().remove(WebAudioID);
        MMKV.defaultMMKV().remove(AudioIndex);
    }

    boolean activate = false;

    public void reset() {
        apsKit.unbindCallBacks();
        activate = false;
        if (audioItem != null && audioItem.articleItem != null) {
            play_progress.setText("00:00");//audioItem.articleItem.getProp4());
//            total_progress.setText("00:00");
        }
        Drawable toggleDrawable = mContext.getResources().getDrawable(R.drawable.insert_audio_playbtn);
        audio_play.normalImg = audio_play.pressImg = toggleDrawable;
        audio_play.updateEffDrawable();
        audioPlayStatus.setImageResource(R.drawable.instert_audio_playstatus);
    }


    @Override
    public void onClick(View v) {

        if (audioItem.streamInfo == null || TextUtils.isEmpty(audioItem.streamInfo.getAddress())) {
            ToastUtil.show(mContext, R.string.no_insert_audiores);
            return;
        }
        if (!activate) {
            MusicEntity entity = new MusicEntity(audioItem.articleItem.getTitle(), audioItem.streamInfo.url);
            apsKit.setData(entity);
            activate = false;
            EventBus.getDefault().post(new StopReadNewsEvent());
         //   KillMusicUtils.hideReadNewsWin();
        }
        if(receiver == null){
            initNetStatusBroad();
        }
        ConnectivityManager cm = SystemServiceManager.getConnectivityManager(mContext);
        @SuppressLint("MissingPermission") NetworkInfo networkInfo = cm.getActiveNetworkInfo();
        if (networkInfo != null && networkInfo.isAvailable()) {
            if (networkInfo.getType() == ConnectivityManager.TYPE_MOBILE) {
                if (MMKV.defaultMMKV().getBoolean(XKey.VIDEO_TIP_KEY, true)) {
                    if (intserAudioActionListener != null) {
                        intserAudioActionListener.checkNetChange(false);
                    }
                    return;
                }
            }
        }
        apsKit.toggle();
        if (intserAudioActionListener != null) {
            intserAudioActionListener.triggerPlayAction(this,apsKit);
            intserAudioActionListener.checkNetChange(false);
        }

    }


    public static class InsertAudioItem {
        public AudioItem streamInfo;

        public ArticleItem articleItem = new ArticleItem();
    }


    public void destroy() {
        if (isDispose)
            return;
        isDispose = true;
        if (getParent() != null) {
            ((ViewGroup) getParent()).removeView(this);
        }
        audio_play.setOnClickListener(null);
        checkFloatingWindowPlay();
        mContext = null;
        audioItem = null;
        intserAudioActionListener = null;
        if (receiver != null) {
            getContext().unregisterReceiver(receiver);
            receiver = null;
        }
    }

    private NetChangeReceiver receiver;
    protected class NetChangeReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intserAudioActionListener != null) {
                intserAudioActionListener.checkNetChange(true);
            }

        }
    }

    public interface IntserAudioActionListener {
        void triggerPlayAction(View view,APSLifecycleKit apsKit);
        void checkNetChange(boolean flag);
    }

    public interface OnPositionListener {
        void onPosition(int audioViewTop);
    }

    /**
     * 判断是否要后台播放
     */
    private void checkFloatingWindowPlay() {
        if (apsKit.isTaskPlaying()) {
            MMKV.defaultMMKV().putLong(WebAudioID, audioItem.articleItem.getId());
            MMKV.defaultMMKV().putInt(AudioIndex, (Integer) getTag());
            sendShowFloaWinMsg();
        } else {
            clear();
        }
    }

    private void startReadNews() {
        if (TextUtils.isEmpty(apsKit.getUrl())) {
            return;
        }
        AudioFloatManager.Companion.getInstance(getContext()).setArticle(audioItem.articleItem);
        AudioFloatManager.Companion.getInstance(getContext()).setCatalogItem(catalogItem);
        AudioFloatManager.Companion.getInstance(getContext()).setTaskId(audioItem.articleItem.getId() + "_" + getTag());
        AudioFloatManager.Companion.getInstance(getContext()).show();

    }

    protected final void sendShowFloaWinMsg() {
        if (PermissionUtils.checkPermission(getContext())) {
            startReadNews();
        } else {
            PermissionUtils.requestPermission((Activity) getContext(), new OnPermissionResult() {
                @Override
                public void permissionResult(boolean isOpen) {
                    startReadNews();
                }
            });
        }
    }

}